import 'package:card_swiper/card_swiper.dart';
import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/entity/home/content/content_data.dart';
import 'package:cbec_app/entity/home/home_data.dart';
import 'package:cbec_app/pages/home/Entity/index_page_ad_entity.dart';
import 'package:cbec_app/pages/home/view/ad_popup.dart';
import 'package:cbec_app/pages/lottery/view/lottery_result_dialog_widget.dart';
import 'package:cbec_app/pages/signIn/sign_in_result_dialog_widget.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import '../../../entity/home/hom_nav_tab_entity.dart';
import '../../../entity/home/navigation_data.dart';
import '../../../entity/lottery/lotter_result_bean.dart';
import '../../../entity/lottery/lottery_bean.dart';
import '../../../entity/lottery/lottery_list_bean.dart';
import '../../../entity/signIn/sign_in_prize_bean.dart';
import '../../../entity/signIn/sign_in_recored_bean.dart';
import '../../../utils/network_helper.dart';
import '../../lottery/view/SimpleLotteryValue.dart';
import '../../lottery/view/lottery_result_fail_dialog_widget.dart';
import '../../lottery/view/lottery_result_list_widget.dart';
import 'package:cbec_app/utils/jpush_tool.dart';

///首页控制器
class HomeController extends BaseController with SingleGetTickerProviderMixin {
  final NetworkHelper _networkHelper = NetworkHelper();
  // 记录当前网络状态
  final Rx<ConnectivityResult> networkStatus = ConnectivityResult.none.obs;

  ///下拉刷新控制器
  RefreshController baseRefreshCtr = RefreshController(initialRefresh: false);

  HomeDataModel? homeDataModel;

  NavigationData? navigation; // 第一个页面 导航数据

  String titleName = '';

  int pageType = 0;

  ContentNavEntity? contentNavEntity;

  List<ContentNavSubEntry> subEntries = [];

  List<String> tabTitles = [];

  ///装修配置
  List<ContentData> contentComponents = [];

  ///导航装修配置
  Map<String, dynamic> navConfig = {};

  String bgColor = '#FFFFFF';

  TabController? tabCtr;

  //是否登录
  bool isLogin = false;

  ///导航是否为沉浸式
  bool isImmersionNav = false;

  ///是否显示导航
  bool isShowNav = false;

  bool isMainPage = false;

  late TabController tabCtrLottery;

  IndexPageAdEntity? indexPageAdEntity;

  void addTabListener() {
    tabCtr?.addListener(() {
      if (tabCtr!.indexIsChanging) {
        final newIndex = tabCtr!.index;
        changeTabIndex(newIndex);
      }
    });
  }

  Future<void> changeTabIndex(int index) async {
    if (index < 0 || index >= subEntries.length) return; // 检查索引有效性

    ContentNavSubEntry navSubEntryModel = subEntries[index];
    try {
      await getNavSingleDecoration(navSubEntryModel.id!);
    } catch (error) {
      // 处理错误
    }
    logger.i('准备更新');
    update(); // 确保在获取数据后更新 UI
  }

  late SimpleLotteryController simpleLotteryController;
  List<String> rewardsList = [];
  LotteryBean? lotteryBean;
  LotteryListBean? lotteryListBean;
  LotterResultBean? lotteryResultBean;
  SignInRecoredBean? signInRecoredBean;
  List<SignInPrizeBean?>? signInPrizesListBean;
  bool isRaffleRefresh = false;
  bool clickEnable = true;
  @override
  void onInit() async {
    super.onInit();
    await getIndexAd();
    await getDecoration();
    tabCtrLottery = TabController(length: 2, vsync: this);
    simpleLotteryController = SimpleLotteryController(rewardsList: rewardsList);
    isLogin = AppData.tokenName != '' ? true : false;

    ///监听登录状态
    EventMgr.on(EventType.refreshLogin, (arg) {
      isLogin = AppData.tokenName != '' ? true : false;
      getDecoration();
      update();
    });

    ///刷新抽奖，直接刷新首页列表
    EventMgr.on(EventType.refreshRaffle, (arg) {
      isRaffleRefresh = true;
      getRaffleConfig();
    });
    //getGuideAd();
    update();

    final JPushTool jpushTool = JPushTool();
    await jpushTool.initializeJPush();
    await jpushTool.getRegistrationID((registrationID) {
      print('极光 registrationID ====== $registrationID');
      if (registrationID != null) {
        AppData.jPushRegistrationID = registrationID;
      }
    });

    UmengCommonSdk.onPageStart('首页');

    _networkHelper.startListening((ConnectivityResult status) {
      print('ConnectivityResult走了没');
      networkStatus.value = status;
      onNetworkStatusChanged(status); // 让子类可以重写处理
    });
  }

  @override
  void onClose() {
    super.onClose();
    EventMgr.off(EventType.refreshLogin);
    EventMgr.off(EventType.refreshRaffle);
    _networkHelper.dispose();
    UmengCommonSdk.onPageEnd('首页');
  }

  void onNetworkStatusChanged(ConnectivityResult status) {
    print('子类可以重写此方法，处理网络状态变');
    print("当前网络状态1: ${NetworkHelper().currentStatus}");
    print("当前网络状态2: $status");
    onInit();
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    await getDecoration();
    // 重置获取数据LoadStatus
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    // setGoodsList(isAdd: true);
    // update();
  }

  ///获取装修配置
  Future getDecoration() {
    Tools.showLoading();
    return Network.getIndexDecorationConfig().then((value) {
      logger.i('result ==== ${value}');
      homeDataModel = HomeDataModel.fromJson(value);
      logger.i('homeDataModel === ${homeDataModel?.toJson()}}');

      titleName = homeDataModel?.name ?? '';
      pageType = homeDataModel?.type ?? 0;

      if (pageType == 1) {
        // 处理类型一
        print('处理类型一 ');
        navConfig = value['navigation'];
        isImmersionNav = navConfig['navigationbar_type'] == 'immersion';
        bgColor = homeDataModel?.config?.color ?? "#F4F4F4";
        // if (homeDataModel?.mainPage == 1) {
        //   navigation = homeDataModel?.navigation;
        // }
        contentComponents = homeDataModel?.content ?? [];
        fetchContentComponentsDataJudgeByType();
        update();
      } else {
        // 处理类型Tab
        contentNavEntity = homeDataModel?.navContent;
        subEntries = homeDataModel?.navContent?.subEntry ?? [];
        print('subEntries ====== $subEntries');
        tabTitles = subEntries.map((item) => item.tagName ?? '').toList();
        print('tabTitles  === $tabTitles');
        tabCtr = TabController(length: tabTitles.length, vsync: this);
        addTabListener(); // 确保在初始化后添加监听

        changeTabIndex(tabCtr!.index);
        update();
      }
      Tools.hideLoading();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///获取装修配置
  Future getRaffleConfig() {
    return Network.getRaffle().then((value) {
      try {
        if (value != null) {
          logger.i('result ====RaffleConfig ${value}');
          lotteryBean = value;
          rewardsList.clear();
          value?.prizeList?.forEach((v) => {rewardsList..add('${v.image}')});
          if (isRaffleRefresh) {
            isRaffleRefresh = false;
            update();
          }
        }
      } catch (e) {
        logger.e(e);
      }
    }).catchError((onError) {
      logger.i('result ====RaffleConfig ${onError}');
    });
  }

  ///获取装修配置
  requestWin() {
    if (!AppData.isLogin) {
      Tools.showToast('请登录');
      return;
    }
    if (lotteryBean == null || lotteryBean?.prizeList == null || lotteryBean!.num == 0) {
      Tools.showToast('抽奖次数不足');
      return;
    }
    if(clickEnable){
      clickEnable = false;
    }else{
      return;
    }
    return Network.getRaffleResult().then((value) {
      logger.i('result ==== ${value?.location}');
      lotteryResultBean = value;
      lotteryBean?.num = value?.prizeCount;
      if (value == null || value.location == null) {
        Tools.showToast('抽奖失败，请联系客服');
        clickEnable = true;
        return;
      }
      int resultIndex = 0;
      for (int i = 0; i < lotteryBean!.prizeList!.length; i++) {
        if (lotteryBean!.prizeList![i].location == value?.location) {
          resultIndex = i;
        }
      }
      if (value.storage == 0) {
        simpleLotteryController.start(target: resultIndex, duration: const Duration(seconds: 3), repeatRound: 3);
        Future.delayed(const Duration(seconds: 4), () => {
          clickEnable = true,
          showResultFailDialog()});
      } else if (value.location != null && (value.name == null || !Tools.checkEmpty(value.name))) {
        simpleLotteryController.start(target: resultIndex, duration: const Duration(seconds: 3), repeatRound: 3);
        Future.delayed(const Duration(seconds: 4), () => {
          clickEnable = true,
          showResultFailDialog()});
      } else {
        simpleLotteryController.start(target: resultIndex, duration: Duration(seconds: 3), repeatRound: 3);
        Future.delayed(const Duration(seconds: 4), () => {
          clickEnable = true,
          showResultDialog()});
      }
      getRaffleConfig();
      update();
    }).catchError((onError) {});
  }

  ///获取装修配置
  Future requestLotteryList() {
    return Network.getRaffleResultList().then((value) {
      logger.i('result ==== ${value}');
      lotteryListBean = value;
      _showResultListDialog();
    }).catchError((onError) {});
  }

  void _showResultListDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            backgroundColor: Colors.transparent,
            child: LotteryResultListWidget(lotteryListBean: lotteryListBean),
          );
        });
  }

  void showResultDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            backgroundColor: Colors.transparent,
            child: LotteryResultDialogWidget(
                lotteryResultBean: lotteryResultBean,
                onPress: () {
                  Navigator.pop(Get.context!);
                  requestWin();
                }),
          );
        });
  }

  //失败
  void showResultFailDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            backgroundColor: Colors.transparent,
            child: LotteryResultFailDialogWidget(
                lotteryResultBean: lotteryResultBean,
                onPress: () {
                  if (lotteryResultBean != null && lotteryResultBean!.prizeCount != null && lotteryResultBean!.prizeCount! > 0) {
                    requestWin();
                  } else {
                    Tools.showToast('抽奖次数不足');
                  }
                }),
          );
        });
  }

  ///进行签到操作
  requestSignInResult() {
    if (!AppData.isLogin) {
      Tools.showToast('请登录');
      return;
    }
    return Network.getSignInResult().then((value) {
      if (value == null) {
        // Tools.showToast('签到成功');
        signInRecoredBean = null;
        requestSignInRecord();
      } else {
        signInPrizesListBean = [];
        value.forEach((v) => {signInPrizesListBean?.add(SignInPrizeBean.fromJson(v))});
        showSignInResultDialog();
      }
    }).catchError((onError) {});
  }

  ///获取签到配置列表
  Future requestSignInRecord() async {
    return Network.getSignInResultRecord().then((value) {
      logger.i('获取签到配置列表result ==== ${value}');
      if (signInRecoredBean == null) {
        signInRecoredBean = value;
        update();
      } else
        signInRecoredBean = value;
    }).catchError((onError) {});
  }

  //签到结果
  void showSignInResultDialog() {
    showDialog(
        context: Get.context!,
        builder: (c) {
          return Dialog(
            insetPadding: EdgeInsets.symmetric(horizontal: 0, vertical: 10),
            backgroundColor: Colors.transparent,
            child: SignInResultDialogWidget(
                prizeList: signInPrizesListBean,
                onPress: () {
                  signInRecoredBean = null;
                  requestSignInRecord();
                }),
          );
        });
  }

  Future getNavSingleDecoration(String id) {
    Tools.showLoading();
    return Network.getMicroConfig(id).then((value) {
      Tools.hideLoading();
      print('单个页面 === $value');
      HomeDataModel homeDataModel = HomeDataModel.fromJson(value);
      bgColor = homeDataModel.config?.color ?? "#F4F4F4";
      isMainPage = homeDataModel.mainPage == 1 ? true : false;
      print('isMainPage ==== $isMainPage');
      if (homeDataModel.mainPage == 1) {
        navigation = homeDataModel.navigation;
      }
      contentComponents = homeDataModel.content ?? [];
      fetchContentComponentsDataJudgeByType();
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///获取引导页广告
  Future getGuideAd() {
    return Network.getGuideAd().then((value) {
      print('获取引导页广告 ==== $value');
      if (value == null) {
        return;
      }
      if (value['app'] == 1) {
        Tools.showDialogAd(Container(
          width: 330,
          height: 331,
          child: guideSwiper(value['content']),
        ));
      }
    });
  }

  ///引导页轮播
  Widget guideSwiper(List adList) {
    return Swiper(
        autoplay: true,
        autoplayDisableOnInteraction: true,
        itemBuilder: (context, index) {
          return BaseImage(url: adList[index]['image_url'], width: 330, fit: BoxFit.contain);
        },
        itemCount: adList.length);
  }

  ///获取主页弹窗广告
  Future<void> getIndexAd() async {
    try {
      final response = await Network.getIndexAd();
      print('获取主页弹窗广告  $response');
      if (response != null) {
        indexPageAdEntity = IndexPageAdEntity.fromJson(response[0]);
        Map data = response[0];
        if (indexPageAdEntity != null && indexPageAdEntity!.mainPage! == 1) {
          showCustomDialog(Get.context!, indexPageAdEntity!.fileUrl!, () {
            if (data['content'] != null) {
              Get.back();
              Map<String, dynamic> contentMap = data['content'];
              Tools.jumpPage(contentMap);
            }
          });
        }
      } else {
        print('获取主页弹窗广告返回空列表');
      }
    } catch (error) {
      print('获取主页弹窗广告失败: $error');
    }
  }

  ///监听页面下滑
  void onScrollDown() {
    isShowNav = true;
    update();
  }

  ///监听页面上拉
  void onScrollTop() {
    isShowNav = false;
    update();
  }

  void fetchContentComponentsDataJudgeByType() {
    for (var item in contentComponents) {
      switch (item.type) {
        case 'raffle':
          if (AppData.isLogin) {
            getRaffleConfig();
          }

          break;
        case 'signin':
          if (AppData.isLogin) {
            requestSignInRecord();
          }
          break;
        default:
          break;
      }
    }
  }
}
